package com.alumni_circle.core.utils;

import cn.hutool.core.util.StrUtil;
import com.alumni_circle.constant.PathConstant;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.name.Rename;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;

/**
 * @author 龙小虬
 * @since 2020-07-10 15:55
 */
public class PictureBase64 {

    public final static String SIZE16 = "16x16";

    public final static String SIZE48 = "48x48";

//    public static String thumbnail(String fileName){
//        String path = PathConstant.SERVER.getPath();
//
//        File orginFile = new File(path);
//        System.out.println(!(new File(path+File.separator+"thumbnail."+fileName).exists()));
//        if(!(new File(path+File.separator+"thumbnail."+fileName).exists())){
//            try {
//                Thumbnails.of(new File(path+"/"+fileName)).size(200,200).toFiles(orginFile,Rename.PREFIX_DOT_THUMBNAIL);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        return path+"/thumbnail."+fileName;
//    }

    public static String thumbnail(String fileName){
        if(StrUtil.hasEmpty(fileName)){
            return null;
        }
        String path = PathConstant.SERVER.getPath();
        String url = PathConstant.URL.getPath();
        File orginFile = new File(path);
        System.out.println((new File(path+File.separator+"thumbnail."+fileName).exists()));
        //文件不存在，创建新文件
        if(new File(path).exists() && !(new File(path+File.separator+"thumbnail."+fileName).exists())){
            try {
                Thumbnails.of(new File(path+File.separator+fileName)).size(400,400).toFiles(orginFile,Rename.PREFIX_DOT_THUMBNAIL);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return url+"/thumbnail."+fileName;
    }

    public static String thumbnailList(String fileName){
        if(StrUtil.hasEmpty(fileName)){
            return null;
        }
        String path = PathConstant.SERVER.getPath();
        String url = PathConstant.URL.getPath();
        String[] str = fileName.split(";");
        String fileUrl = "";
        for (int i = 0; i < str.length; i++) {
            if(StrUtil.hasEmpty(str[i])){
                continue;
            }
            File orginFile = new File(path);
            System.out.println((new File(path+File.separator+"thumbnail."+str[i]).exists()));
            //文件不存在，创建新文件
            if(new File(path).exists() && !(new File(path+File.separator+"thumbnail."+str[i]).exists())){
                try {
                    Thumbnails.of(new File(path + File.separator + str[i])).size(200, 200).toFiles(orginFile, Rename.PREFIX_DOT_THUMBNAIL);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(i!=str.length-1){
                fileUrl += url+"/thumbnail."+str[i]+";";
            }else {
                fileUrl += url+"/thumbnail."+str[i];
            }
        }
        return fileUrl;
    }

    /**
     * 将base64编码字符串转换为图片,并保存在path
     */
    public static String strImage(String imgStr, String path) {
        if (StrUtil.hasEmpty(imgStr)) {
            return null;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        imgStr.replace("\n","");
        try {
            // 解密
            byte[] b = decoder.decodeBuffer(imgStr);
            // 处理数据
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            OutputStream out = new FileOutputStream(path);
            out.write(b);
            out.flush();
            out.close();
            return path;
        } catch (Exception e) {
            return "fail";
        }
    }

//    public static void main(String[] args) throws IOException {
//        String base = new String(Base64.getDecoder().decode("eyJpYXQiOjE1OTY1MjEwOTMsImV4cCI6MTU5NjUyMTM5Mywic3ViIjoiZTcwMDNiN2UyN2JmNDQ0YWE1NmI1NTJjMzRmYjIwYTEiLCJhdXRob3JpdGllcyI6IuinkuiJsiJ9"), StandardCharsets.UTF_8);
//        System.out.println(base);
//    }

    /**
     * 根据图片地址转换为base64编码字符串
     * 拿取原图路径
     */
    public static String imageListStr(String imgFile) {
        if(StrUtil.hasEmpty(imgFile)){
            return null;
        }
        String []image = imgFile.split(";");
        BASE64Encoder encoder = new BASE64Encoder();
        StringBuilder str= new StringBuilder();
        for (int i = 0; i < image.length; i++) {
            if((";").equals(image[i])){
                continue;
            }
            InputStream inputStream = null;
            byte[] data = null;
            try {
//                if(!new File(image[i]).exists()){
//                    return null;
//                }
                image[i] = thumbnail(image[i]);
                inputStream = new FileInputStream(image[i]);
                data = new byte[inputStream.available()];
                inputStream.read(data);
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if(i!=image.length-1){
                assert data != null;
                str.append(encoder.encode(data)).append(";");
            }else{
                assert data != null;
                str.append(encoder.encode(data));
            }
        }
        return str.toString().replaceAll("\n","");
    }


    /**
     * 根据图片地址转换为base64编码字符串
     */
    public static String imageStr(String imgFile) {
        if(StrUtil.hasEmpty(imgFile)){
            return null;
        }
        imgFile.replaceAll(";","");
        InputStream inputStream = null;
        byte[] data = null;
        try {
//            if(!new File(imgFile).exists()){
//                return null;
//            }
            imgFile = thumbnail(imgFile);
            inputStream = new FileInputStream(imgFile);
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 加密
        BASE64Encoder encoder = new BASE64Encoder();
        assert data != null;
        String str = encoder.encode(data);
        return str.replaceAll("\n","");
    }


    public static void copyImage(String imgFile) throws IOException{
        FileInputStream fis = new FileInputStream(imgFile);
        FileOutputStream fos = new FileOutputStream(imgFile);

        int len;
        byte[] bys = new byte[1024];
        while((len = fis.read(bys)) != -1) {
            fos.write(bys, 0, len);
        }
        fis.close();
        fos.close();
    }

}
